package cn.edu.ctbu.simplescoremanagementsystem.webapi;

import cn.edu.ctbu.simplescoremanagementsystem.core.PageUtils;
import cn.edu.ctbu.simplescoremanagementsystem.domain.Course;
import cn.edu.ctbu.simplescoremanagementsystem.domain.Student;
import cn.edu.ctbu.simplescoremanagementsystem.service.CourseService;
import cn.edu.ctbu.simplescoremanagementsystem.utils.ResultUtils;
import cn.edu.ctbu.simplescoremanagementsystem.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/webapi/course")
public class CourseRestController {
    @Autowired
    CourseService courseService;
    @GetMapping("/findAll")
    public Result<List<Course>> findAll(){
        List<Course> courses = courseService.findAll();
        return ResultUtils.success(courses);
    }

    @PostMapping("/insert")
    public Result<List<Course>> insert(){
        List<Course> courses = courseService.findAll();
        return ResultUtils.success();
    }

    @GetMapping("/getByPage")
    public Result<PageUtils> getByPage(@RequestParam(value = "page",defaultValue = "0")Integer page,
                                       @RequestParam(value = "size",defaultValue = "7")Integer size,
                                       @RequestParam(value = "name",defaultValue = "")String name,
                                       @RequestParam(value = "no",defaultValue = "")String no){
        Sort sort = Sort.by(Sort.Direction.ASC, "id");//排序
        Page<Course> coursePage;
        Pageable pageable = PageRequest.of(page,size,sort);
        if(StringUtils.isEmpty(name)&&StringUtils.isEmpty(no)){
            coursePage = courseService.getByPage(pageable);
        }else{
            Course course = new Course();
            ExampleMatcher matcher = null;
            if(!StringUtils.isEmpty(name)){
                course.setCname(name);
                matcher = ExampleMatcher.matching()
                        .withMatcher("cname",ExampleMatcher.GenericPropertyMatchers.contains());//模糊查询包含，即%{username}%
            }
            if(!StringUtils.isEmpty(no)){
                course.setCno(no);
                matcher = ExampleMatcher.matching()
                        .withMatcher("cno",ExampleMatcher.GenericPropertyMatchers.contains());//模糊查询包含，即%{username}%
            }


            Example<Course> example = Example.of(course,matcher);//模糊查询
            coursePage = courseService.getByPage(example,pageable);
        }
        PageUtils pageUtils = new PageUtils(coursePage.getContent(),coursePage.getTotalElements());
        return ResultUtils.success(pageUtils);
    }
}
